<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.podName" placeholder="Pod名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.namespace" placeholder="命名空间" clearable style="width: 150px" class="filter-item" @change="handleNamespaceChange">
        <el-option v-for="item in namespaceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.status" placeholder="状态筛选" clearable style="width: 150px" class="filter-item">
        <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" :disabled="!listQuery.namespace" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" :disabled="!listQuery.namespace" @click="handleCreate">
        创建
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-refresh" @click="refreshList">
        刷新
      </el-button>
    </div>

    <el-alert
      v-if="!listQuery.namespace"
      title="请先选择命名空间"
      type="warning"
      :closable="false"
      style="margin-bottom: 15px;"
    />

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="pagedList"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="Pod名称" min-width="180px" align="center">
        <template slot-scope="{row}">
          <span class="link-type" @click="handlePodDetail(row)">{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="命名空间" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ listQuery.namespace }}</span>
        </template>
      </el-table-column>
      <el-table-column label="节点" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.node || 'N/A' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="IP地址" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.IP || 'N/A' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="就绪状态" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="getReadyStatusType(row.ready)">
            {{ row.ready }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="getStatusType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="重启次数" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.restarts || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="运行时间" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ formatAge(row.age) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="handlePagination" />

    <!-- 创建Pod对话框 -->
    <el-dialog title="创建Pod" :visible.sync="createDialogVisible" width="600px" :close-on-click-modal="false">
      <el-form ref="createForm" :model="createForm" :rules="createRules" label-width="120px">
        <el-form-item label="Pod名称" prop="podname">
          <el-input v-model="createForm.podname" placeholder="请输入Pod名称" />
          <div class="form-tip">只能包含小写字母、数字和-，以字母开头和结尾</div>
        </el-form-item>
        <el-form-item label="命名空间" prop="namespace">
          <el-select v-model="createForm.namespace" placeholder="请选择命名空间" style="width: 100%;">
            <el-option v-for="item in namespaceOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="容器名称" prop="imagename">
          <el-input v-model="createForm.imagename" placeholder="请输入容器名称" />
        </el-form-item>
        <el-form-item label="镜像地址" prop="image">
          <el-input v-model="createForm.image" placeholder="请输入镜像地址，如：nginx:latest" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="createLoading" @click="handleCreateConfirm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑Pod对话框 -->
    <el-dialog title="编辑Pod" :visible.sync="editDialogVisible" width="600px" :close-on-click-modal="false">
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="120px">
        <el-form-item label="Pod名称">
          <span>{{ editForm.podname }}</span>
        </el-form-item>
        <el-form-item label="命名空间">
          <span>{{ editForm.namespace }}</span>
        </el-form-item>
        <el-form-item label="容器名称" prop="imagename">
          <el-input v-model="editForm.imagename" placeholder="请输入容器名称" />
        </el-form-item>
        <el-form-item label="镜像地址" prop="image">
          <el-input v-model="editForm.image" placeholder="请输入镜像地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleEditConfirm">确定</el-button>
      </div>
    </el-dialog>

    <!-- Pod详情对话框 -->
    <el-dialog title="Pod详情" :visible.sync="detailDialogVisible" width="80%" top="5vh">
      <el-descriptions v-if="currentPod" :column="2" border>
        <el-descriptions-item label="名称">{{ currentPod.name }}</el-descriptions-item>
        <el-descriptions-item label="命名空间">{{ currentPod.namespace }}</el-descriptions-item>
        <el-descriptions-item label="节点">{{ currentPod.node || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ currentPod.IP || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentPod.status)">
            {{ currentPod.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="运行时间">{{ formatAge(currentPod.age) }}</el-descriptions-item>
        <el-descriptions-item label="容器信息" :span="2">
          <el-table :data="currentPod.containers" border style="width: 100%">
            <el-table-column prop="name" label="容器名称" width="150" />
            <el-table-column prop="image" label="镜像" />
            <el-table-column prop="imagePullPolicy" label="镜像拉取策略" width="120" />
          </el-table>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPodList,
  deletePod,
  createPod,
  updatePod,
  getPodDetail
} from '@/api/k8sPods'
import { getNameSpaceList } from '@/api/k8sNamespace'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'

export default {
  name: 'PodList',
  components: { Pagination },
  directives: { waves },

  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        podName: undefined,
        namespace: undefined,
        status: undefined
      },
      namespaceOptions: [],
      statusOptions: ['Running', 'Pending', 'Succeeded', 'Failed', 'Unknown'],

      // 创建对话框相关
      createDialogVisible: false,
      createLoading: false,
      createForm: {
        podname: '',
        namespace: '',
        imagename: '',
        image: ''
      },
      createRules: {
        podname: [
          { required: true, message: '请输入Pod名称', trigger: 'blur' },
          { pattern: /^[a-z]([-a-z0-9]*[a-z0-9])?$/, message: '名称格式不正确', trigger: 'blur' }
        ],
        namespace: [
          { required: true, message: '请选择命名空间', trigger: 'change' }
        ],
        imagename: [
          { required: true, message: '请输入容器名称', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '请输入镜像地址', trigger: 'blur' }
        ]
      },

      // 编辑对话框相关
      editDialogVisible: false,
      editLoading: false,
      editForm: {
        podname: '',
        namespace: '',
        imagename: '',
        image: ''
      },
      editRules: {
        imagename: [
          { required: true, message: '请输入容器名称', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '请输入镜像地址', trigger: 'blur' }
        ]
      },

      // 详情对话框相关
      detailDialogVisible: false,
      currentPod: null
    }
  },

  computed: {
    /**
     * 计算分页后的数据
     */
    pagedList() {
      const { page, limit } = this.listQuery
      const start = (page - 1) * limit
      const end = page * limit
      return this.list.slice(start, end)
    }
  },

  created() {
    this.getNamespaces()
  },

  methods: {
    /**
     * 获取Pod列表
     */
    getList() {
      if (!this.listQuery.namespace) {
        this.list = []
        this.total = 0
        return
      }

      this.listLoading = true
      getPodList(this.listQuery.namespace)
        .then(response => {
          if (response.code === 20000) {
            let podList = response.podList || []

            // 名称筛选
            if (this.listQuery.podName) {
              podList = podList.filter(pod =>
                pod.name.toLowerCase().includes(this.listQuery.podName.toLowerCase())
              )
            }

            // 状态筛选
            if (this.listQuery.status) {
              podList = podList.filter(pod => pod.status === this.listQuery.status)
            }

            this.list = podList
            this.total = this.list.length

            // 如果当前页没有数据且不是第一页，则跳转到前一页
            if (this.pagedList.length === 0 && this.listQuery.page > 1) {
              this.listQuery.page -= 1
            }
          } else {
            this.$message.error(response.message || '获取列表失败')
          }
          this.listLoading = false
        })
        .catch(error => {
          console.error('获取Pod列表失败:', error)
          this.listLoading = false
          this.$message.error('获取Pod列表失败')
        })
    },

    /**
     * 处理分页变化
     */
    handlePagination(paginationData) {
      this.listQuery.page = paginationData.page
      this.listQuery.limit = paginationData.limit
      // 不需要重新调用getList，因为pagedList是计算属性会自动更新
    },

    /**
     * 获取命名空间列表
     */
    getNamespaces() {
      getNameSpaceList()
        .then(response => {
          if (response.code === 20000) {
            this.namespaceOptions = response.nameSpaceList.map(ns => ns.name)
          }
        })
        .catch(error => {
          console.error('获取命名空间失败:', error)
        })
    },

    /**
     * 处理命名空间变更
     */
    handleNamespaceChange() {
      this.listQuery.page = 1
      this.getList()
    },

    /**
     * 处理搜索筛选
     */
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    /**
     * 刷新数据列表
     */
    refreshList() {
      this.getList()
      this.$message.success('数据已刷新')
    },

    /**
     * 处理创建Pod
     */
    handleCreate() {
      this.createForm = {
        podname: '',
        namespace: this.listQuery.namespace,
        imagename: '',
        image: ''
      }
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs.createForm && this.$refs.createForm.clearValidate()
      })
    },

    /**
     * 确认创建Pod
     */
    handleCreateConfirm() {
      this.$refs.createForm.validate((valid) => {
        if (valid) {
          this.createLoading = true

          // 直接使用表单数据，字段名已经符合后端要求
          const requestData = { ...this.createForm }

          console.log('发送的创建数据:', requestData)

          createPod(requestData)
            .then(response => {
              if (response.code === 20000) {
                this.$message.success('创建成功')
                this.createDialogVisible = false
                this.getList()
              } else {
                this.$message.error(response.message || '创建失败')
              }
              this.createLoading = false
            })
            .catch(error => {
              console.error('创建Pod失败:', error)
              this.$message.error('创建Pod失败: ' + (error.response?.data?.error || error.message))
              this.createLoading = false
            })
        } else {
          this.$message.warning('请填写完整的表单信息')
        }
      })
    },

    /**
     * 处理编辑Pod
     */
    handleEdit(row) {
      // 先获取Pod详情来填充镜像信息
      getPodDetail(this.listQuery.namespace, row.name)
        .then(response => {
          if (response.code === 20000) {
            this.editForm = {
              podname: row.name,
              namespace: this.listQuery.namespace,
              imagename: response.containers?.[0]?.name || '',
              image: response.containers?.[0]?.image || ''
            }
            this.editDialogVisible = true
            this.$nextTick(() => {
              this.$refs.editForm && this.$refs.editForm.clearValidate()
            })
          } else {
            this.$message.error('获取Pod详情失败')
          }
        })
        .catch(error => {
          console.error('获取Pod详情失败:', error)
          this.$message.error('获取Pod详情失败')
        })
    },

    /**
     * 确认编辑Pod
     */
    handleEditConfirm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.editLoading = true

          const requestData = { ...this.editForm }
          console.log('发送的更新数据:', requestData)

          updatePod(requestData)
            .then(response => {
              if (response.code === 20000) {
                this.$message.success('更新成功')
                this.editDialogVisible = false
                this.getList()
              } else {
                this.$message.error(response.message || '更新失败')
              }
              this.editLoading = false
            })
            .catch(error => {
              console.error('更新Pod失败:', error)
              this.$message.error('更新Pod失败: ' + (error.response?.data?.error || error.message))
              this.editLoading = false
            })
        } else {
          this.$message.warning('请填写完整的表单信息')
        }
      })
    },

    /**
     * 处理删除Pod操作
     */
    handleDelete(row) {
      this.$confirm(`确定要删除Pod "${row.name}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePod(this.listQuery.namespace, row.name)
          .then(response => {
            if (response.code === 20000) {
              this.$message.success('删除成功')
              this.getList()
            } else {
              this.$message.error(response.message || '删除失败')
            }
          })
          .catch(error => {
            console.error('删除Pod失败:', error)
            this.$message.error('删除Pod失败')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    /**
     * 查看Pod详情 - 修正版本
     */
    handlePodDetail(row) {
      getPodDetail(this.listQuery.namespace, row.name)
        .then(response => {
          console.log('详情API响应:', response) // 调试信息
          if (response.code === 20000) {
            // 修正：直接使用response，而不是response.data
            this.currentPod = {
              name: response.name,
              namespace: response.namespace,
              node: response.node,
              IP: response.IP,
              status: response.status,
              age: response.age,
              containers: response.containers || []
            }
            this.detailDialogVisible = true
          } else {
            this.$message.error(response.message || '获取详情失败')
          }
        })
        .catch(error => {
          console.error('获取Pod详情失败:', error)
          this.$message.error('获取Pod详情失败: ' + (error.response?.data?.error || error.message))
        })
    },

    /**
     * 获取就绪状态类型
     */
    getReadyStatusType(ready) {
      if (!ready) return 'danger'
      const [readyCount, totalCount] = ready.split('/').map(Number)
      if (readyCount === totalCount) return 'success'
      if (readyCount === 0) return 'danger'
      return 'warning'
    },

    /**
     * 获取状态类型
     */
    getStatusType(status) {
      const statusMap = {
        'Running': 'success',
        'Pending': 'warning',
        'Succeeded': 'info',
        'Failed': 'danger',
        'Unknown': 'danger'
      }
      return statusMap[status] || 'info'
    },

    /**
     * 格式化运行时间 - 修复版本
     */
    formatAge(age) {
      if (!age) return '-'

      // 如果age是时间戳格式
      if (typeof age === 'number' && age > 1000000000000) {
        const now = Date.now()
        const diff = now - age

        const seconds = Math.floor(diff / 1000)
        const minutes = Math.floor(seconds / 60)
        const hours = Math.floor(minutes / 60)
        const days = Math.floor(hours / 24)

        if (days > 0) return `${days}天${hours % 24}小时`
        if (hours > 0) return `${hours}小时${minutes % 60}分钟`
        if (minutes > 0) return `${minutes}分钟${seconds % 60}秒`
        return `${seconds}秒`
      }

      // 如果age是字符串格式（如 "2d3h4m5s"）
      if (typeof age === 'string') {
        // 解析Kubernetes风格的时间格式
        let totalSeconds = 0

        // 匹配天、小时、分钟、秒
        const dayMatch = age.match(/(\d+)d/)
        const hourMatch = age.match(/(\d+)h/)
        const minuteMatch = age.match(/(\d+)m/)
        const secondMatch = age.match(/(\d+)s/)

        if (dayMatch) totalSeconds += parseInt(dayMatch[1]) * 24 * 60 * 60
        if (hourMatch) totalSeconds += parseInt(hourMatch[1]) * 60 * 60
        if (minuteMatch) totalSeconds += parseInt(minuteMatch[1]) * 60
        if (secondMatch) totalSeconds += parseInt(secondMatch[1])

        const days = Math.floor(totalSeconds / (24 * 60 * 60))
        const hours = Math.floor((totalSeconds % (24 * 60 * 60)) / (60 * 60))
        const minutes = Math.floor((totalSeconds % (60 * 60)) / 60)
        const seconds = totalSeconds % 60

        if (days > 0) return `${days}天${hours}小时`
        if (hours > 0) return `${hours}小时${minutes}分钟`
        if (minutes > 0) return `${minutes}分钟${seconds}秒`
        return `${seconds}秒`
      }

      return age // 如果无法解析，直接返回原值
    }
  }
}
</script>

<style scoped>
.link-type {
  color: #409EFF;
  cursor: pointer;
}

.link-type:hover {
  text-decoration: underline;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>
